package com.romin.task;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.htmlunit.HtmlUnitWebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.romin.model.LoginUserBean;
import com.romin.service.AcountService;
import com.romin.util.HisoftWorkTypeUtil;
import com.romin.util.HisoftWorkTypeUtil.HisoftWorkType;

@Component
public class HisoftHourTask implements Task, Runnable {
    @Resource
    private AcountService acountService;
    private final static Logger logger = LoggerFactory.getLogger(HisoftHourTask.class);
    protected WebDriver webdriver;
    private static String LOGIN_URL = "http://osplat.asiainfo-linkage.com/osplat/timesheet/Login.aspx";
    private List<LoginUserBean> userBeans;

    public static void main(String[] args) {

        new HisoftHourTask().execute();
    }

    public HisoftHourTask() {
    }

    public HisoftHourTask(List<LoginUserBean> list, AcountService acountService) {
        this.userBeans = list;
        this.acountService = acountService;
    }

    public void writerWorkHour(LoginUserBean bean) {
        logger.info("get login form");
        webdriver.get(LOGIN_URL);
        logger.info("start login");
        webdriver.findElement(By.id("TextBoxUserName")).sendKeys(bean.getUserName());
        webdriver.findElement(By.id("TextBoxPwd")).sendKeys(bean.getPassword());
        webdriver.findElement(By.id("LinkButton_Login")).click();

        //选择最后的一个工时填写区间
        try{
            webdriver.findElement(By.xpath("//select[@id='DropdownlistTimeSheetCode']/option[last()]")).click();
        } catch (NoSuchElementException e) {
            logger.error("user[{}] is not exist or the password is wrong.", bean.getUserName());
            return;
        }

        logger.info("login success,get the write page");
        if (!webdriver.findElement(By.id("HyperLinkButtonFillTime_HyperLinkAction")).isEnabled()) {
            acountService.signAcount(bean.getId());
            logger.error("user[{}] had writen work hour.", bean.getUserName());
            return;
        }
        webdriver.findElement(By.id("HyperLinkButtonFillTime_HyperLinkAction")).click();
        String curHandle = webdriver.getWindowHandle();
        Set<String> handles = webdriver.getWindowHandles();
        for (String s : handles) {
            if (!s.equals(curHandle)) {
                webdriver.switchTo().window(s);
            }
        }
        webdriver.findElement(By.id("HyperLinkButtonAddRow_HyperLinkAction")).click();
        HisoftWorkType workType = HisoftWorkTypeUtil.getCurWorkType();

        logger.info("start write work hour");
        //选择请假或者调休
        HtmlUnitWebElement ele = (HtmlUnitWebElement) webdriver.findElement(By.id("DropDownListWorkType_0"));
        HtmlSelect option = (HtmlSelect) ele.getCoordinates().getAuxiliry();
        option.setSelectedAttribute(workType.getValue(), true);
        webdriver.findElement(By.id("TextBoxRemarks_0")).sendKeys(workType.getName());
        webdriver.findElement(By.id("LinkButtonSubmitDown_LinkButtonAction")).click();
        acountService.signAcount(bean.getId());
        logger.info("user[{}] has well done.",bean.getUserName());
    }

    public void init() {
        webdriver = new HtmlUnitDriver(true);
        webdriver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS).setScriptTimeout(10, TimeUnit.SECONDS);
    }

    public void processTask() {
        for (LoginUserBean b : userBeans) {
            logger.info("user[{}] start login.", b.getUserName());
            writerWorkHour(b);
        }
    }

    @Override
    public void execute() {
        List<LoginUserBean> users = acountService.getLoginBean();
        logger.info("start write hisoft WorkHour,to excute task number:{}", users.size());
        new Thread(new HisoftHourTask(users, this.acountService)).start();
    }
    public void destroy() {
        webdriver.close();
        webdriver.quit();
    }

    @Override
    public void run() {
        init();
        processTask();
        destroy();
    }

    public List<LoginUserBean> getUserBeans() {
        return userBeans;
    }

    public void setUserBeans(List<LoginUserBean> userBeans) {
        this.userBeans = userBeans;
    }

}
